package cn.softgame.jserver.connector.udp;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.Set;

/**
 * UDP数据包接受
 * @author xuquan
 * 日期:2013-5-28
 */
public class UDPReactor implements Runnable{

	private Selector selector;
	
	public UDPReactor(int port) throws IOException{
		selector = Selector.open();
		InetSocketAddress address = new InetSocketAddress(InetAddress.getLocalHost(), port);
		DatagramChannel dc = openDatagramChannel();
		dc.socket().bind(address);
		SelectionKey key = dc.register(selector, SelectionKey.OP_READ);
		key.attach(new UDPHandler(key,dc));
	}
	
	private DatagramChannel openDatagramChannel() {
		DatagramChannel dc = null;
		try {
			dc = DatagramChannel.open();
			dc.configureBlocking(false);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return dc;
	}

	@Override
	public void run() {
		try {
			while(!Thread.interrupted()){
				selector.select();
				Set<SelectionKey> selected = selector.selectedKeys();
				Iterator<SelectionKey> iter = selected.iterator();
				while(iter.hasNext()){
					dispatch(iter.next());
				}
				selected.clear();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void dispatch(SelectionKey sk) {
		Runnable r = (Runnable) sk.attachment();
		if(r!=null){
			r.run();
		}
	}

}
